package us.versus.them.kitkattoe;

import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.MovieClip;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.media.Sound;

enum Ends { me; yu; ti; }

/**
 *
 * <p>
 * App it up, yo!
 * </p>
 *
 */
class App {

	var clip:MovieClip;
	var current:Base;
	var cats:Array< DisplayObject >;
	var meow:Sound;

	var win:Int;
	var lose:Int;
	var tied:Int;

	public function new( ?clip:MovieClip ) {
		this.current = null;
		this.clip = if ( null == clip ) {
			flash.Lib.current;
		} else {
			clip;
		}
		clip = this.clip;

		var thiz = this;
		mochi.as3.MochiAd.showPreGameAd( MochiSettings.get( preGameAdDone, this.clip ) );
	}

	public function preGameAdDone() {
		this.makeCurrent( new Loading( this ) );

		this.cats = new Array< DisplayObject >();
		for ( i in 1...7 ) {
			cats.push( Base.displayObjectForName( 'cat' + i ) );
		}
		this.meow = null;
		//this.meow = Base.soundForName( 'meow' );

		this.makeCurrent( new StartGame( this, cats, meow ) );
	}

	public function newGame() {
		Base.shuffle( cats );
		var me = Base.displayObjectToBitMapData( cats[ 0 ] );
		var yu = Base.displayObjectToBitMapData( cats[ 1 ] );
		//this.makeCurrent( new Game( this, me, yu, meow, this.win, this.lose, this.tied ) );
		this.makeCurrent( new Versus( this, me, yu ) );
	}

	public function versus_done( me, yu ) {
		this.makeCurrent( new Game( this, me, yu, meow, this.win, this.lose, this.tied ) );
	}

	public function nuGame() {
		if ( Math.random() < 0.2 ) {
			mochi.as3.MochiAd.showInterLevelAd( MochiSettings.get( newGame, this.clip ) );
		} else {
			this.newGame();
		}
	}

	public function gameOver( end:Ends ) {
		switch( end ) {
			case me: lose++; 
			case yu: win++; 
			default: tied++;
		}
		this.makeCurrent( new GameOver( this, end ) );
	}

	public function makeCurrent( base:Base ) {
		if ( null == this.current ) {
			//trace( 'there was nothing before...' );
		} else {
			//trace( 'remove ' + this.current + ': ' + Date.now() );
			this.current.removeEventListeners();
			this.clip.removeChild( this.current );
		} 
		this.current = base;
		//trace( 'add ' + this.current + ': ' + Date.now() );
		this.clip.addChild( this.current );
		this.current.init();
	}
}
